//
//  NewsDetailTableView.m
//  item-NetEaseNews-tyw
//
//  Created by tyw on 15/10/2.
//  Copyright (c) 2015年 tyw. All rights reserved.
//

#import "NewsDetailTableView.h"
#import "NewsDetailTableViewCell.h"
#import "RelativeNewsTableView.h"

@implementation NewsDetailTableView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
        self.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        self.delegate = self;
        self.dataSource = self;
        
        self.backgroundColor = [UIColor clearColor];
        
        [self registerClass:[NewsDetailTableViewCell class] forCellReuseIdentifier:kNewsDetailTableViewCellId];
    }
    
    return self;
}

#pragma mark - 数据的set方法
- (void)setNewsDetailModel:(NewsDetailModel *)newsDetailModel {
    if (_newsDetailModel != newsDetailModel) {
        _newsDetailModel = newsDetailModel;
        
        [self resetHeaderView];
        [self resetFooterView];
        [self reloadData];
    }
}

#pragma mark - 重新设置头部、尾部视图。
//头部视图，包括了新闻标题、时间、来源、新闻简介
- (void)resetHeaderView {
    UIView* tableHeaderView = [[UIView alloc] init];
    tableHeaderView.backgroundColor = [UIColor clearColor];
    //新闻标题
    UILabel* titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, -5, kWidth-20, 20)];
    titleLabel.text = _newsDetailModel.newsTitle;
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont boldSystemFontOfSize:18];
    [tableHeaderView addSubview:titleLabel];
    //新闻时间和来源
    UILabel* timeSourceLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 20, kWidth-20, 15)];
    NSString* timeStr = _newsDetailModel.createTime;
    timeSourceLabel.text = [NSString stringWithFormat:@"%@   %@", [timeStr substringWithRange:NSMakeRange(5, 11)], _newsDetailModel.source];
    timeSourceLabel.textColor = [UIColor grayColor];
    timeSourceLabel.font = [UIFont boldSystemFontOfSize:14];
    [tableHeaderView addSubview:timeSourceLabel];
    //新闻简介，时有时无
    //新闻简介的高度
    CGFloat height = [Tools contentSizeWithMaxWidth:kWidth-40 text:_newsDetailModel.newsIntroduce fontOfSize:13].height;
    if (_newsDetailModel.newsIntroduce.length) {
        //位于新闻简介左边的灰色竖条
        UIImageView* grayView = [[UIImageView alloc] initWithFrame:CGRectMake(10, 43, 5, height+10)];
        UIImage* grayImg = [UIImage imageNamed:@"hotspots_content_cell_background"];
        [grayImg stretchableImageWithLeftCapWidth:30 topCapHeight:1];
        grayView.image = grayImg;
        [tableHeaderView addSubview:grayView];
        
        //新闻简介
        UILabel* introduceLabel = [[UILabel alloc] initWithFrame:CGRectMake(25, 46, kWidth-40, height+5)];
        introduceLabel.textColor = [UIColor grayColor];
        introduceLabel.font = [UIFont boldSystemFontOfSize:13];
        introduceLabel.numberOfLines = 2;
        introduceLabel.attributedText = [Tools attributedStrFromStr:_newsDetailModel.newsIntroduce lineSpace:4];
        [introduceLabel sizeToFit];
        [tableHeaderView addSubview:introduceLabel];
    } else {height = 0;}
    
    [tableHeaderView setFrame:CGRectMake(0, 0, kWidth, 50+height)];        //给头部视图加高
    self.tableHeaderView = tableHeaderView;     //这句话必须写在最后
}
//尾部视图，包括了分享（易信、微信、新浪微博、更多）、相关新闻
- (void)resetFooterView {
    UIView* tableFooterView = [[UIView alloc] init];
    tableFooterView.userInteractionEnabled = YES;
    
    //分享，几个按钮，放着看看而已
    CGFloat lineWidth = (kWidth-40)/2;
    UIImage* lineImg = [UIImage imageNamed:@"home_channel_bar_line"];
    [lineImg stretchableImageWithLeftCapWidth:1 topCapHeight:1];
    //两条细线
    UIImageView* line1 = [[UIImageView alloc] initWithFrame:CGRectMake(10, 4.5, lineWidth, 1)];
    line1.image = lineImg;
    [tableFooterView addSubview:line1];
    UIImageView* line2 = [[UIImageView alloc] initWithFrame:CGRectMake(kWidth-10-lineWidth, 4.5, lineWidth, 1)];
    line2.image = lineImg;
    [tableFooterView addSubview:line2];
    //“分享”字样
    UILabel* shareLabel = [[UILabel alloc] initWithFrame:CGRectMake(10+lineWidth, 0, 20, 10)];
    shareLabel.textColor = [UIColor grayColor];
    shareLabel.font = [UIFont systemFontOfSize:10];
    shareLabel.text = @"分享";
    shareLabel.textAlignment = NSTextAlignmentCenter;
    [tableFooterView addSubview:shareLabel];
    //四个按钮，易信、微信、新浪微博、更多
    NSArray* btnImgName = @[@"share_platform_yixintimeline",
                            @"share_platform_wechattimeline",
                            @"share_platform_sina",
                            @"newscontent_share_more"];
    NSArray* labelName = @[@"易信朋友圈",@"微信朋友圈",@"新浪微博",@"更多"];
    CGFloat btnWidth = kWidth/4-50;
    CGFloat labelWidth = kWidth/4-25;
    for (int i = 0; i < 4; i++) {
        //按钮
        UIButton* button = [[UIButton alloc] initWithFrame:CGRectMake(40*(i+1)+btnWidth*i, 20, btnWidth, btnWidth)];
        [button setImage:[UIImage imageNamed:btnImgName[i]] forState:UIControlStateNormal];
        [tableFooterView addSubview:button];
        //按钮类型
        UILabel* label = [[UILabel alloc] initWithFrame:CGRectMake(20*(i+1)+labelWidth*i, 20+btnWidth+5, labelWidth, 15)];
        label.text = labelName[i];
        label.center = CGPointMake(button.center.x, button.center.y+btnWidth/2+5+7.5);
        label.textAlignment = NSTextAlignmentCenter;
        label.textColor = [UIColor grayColor];
        label.font = [UIFont systemFontOfSize:10];
        [tableFooterView addSubview:label];
    }
    
    //相关新闻,时有时无
    CGFloat relativeTableViewHeight = 0;
    if (_newsDetailModel.relativeNewsArray.count > 0) {
        //计算相关新闻所需要的高度.每一条新闻80，“相关新闻”字样和关键字 80.
        relativeTableViewHeight = (_newsDetailModel.relativeNewsArray.count+1)*80;
        RelativeNewsTableView* relativeTableView = [[RelativeNewsTableView alloc] initWithFrame:CGRectMake(0, 20+btnWidth+5+15+20, kWidth, relativeTableViewHeight)];
        relativeTableView.keyWords = _newsDetailModel.keyWords;
        relativeTableView.relativeNewsArray = _newsDetailModel.relativeNewsArray;
        [tableFooterView addSubview:relativeTableView];
    }

    //设置尾部视图的高度
    [tableFooterView setFrame:CGRectMake(0, 0, kWidth, relativeTableViewHeight+10+btnWidth+20+20)];
    self.tableFooterView = tableFooterView;
}

#pragma mark - tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    NSString* newsBody = _newsDetailModel.newsBody;
    //一段文字(可能是文字+图片)、推荐阅读    总是以 <p> 开始 ， 以 <\/p> 结束.
    //这里要注意，如果第一个元素是：“”。不予考虑
    //第一个元素也有可能直接就是图片，长这样<!--IMG#0--><!--IMG#1-->
    NSArray* array = [newsBody componentsSeparatedByString:@"<p>"];
//    if (array.count) {
//        NSString* firStr = array[0];
//        if (firStr.length == 0) {
//            NSMutableArray* newArray = [array mutableCopy];
//            [newArray removeObjectAtIndex:0];
//            array = nil;
//            array = [newArray copy];
//        }
//    }
   
    return array.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NewsDetailTableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:kNewsDetailTableViewCellId forIndexPath:indexPath];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;        //不能被选择
    cell.linkInfoArray = _newsDetailModel.linkInfoArray;
    
    NSString* newsBody = _newsDetailModel.newsBody;
    NSArray* cellContentArray = [newsBody componentsSeparatedByString:@"<p>"];
    
    NSString* thisCellContent = cellContentArray[indexPath.row];        //这个cell的内容
    if (thisCellContent.length >= 4) {          //虽然我知道他一定存在
        NSString* str = [thisCellContent substringFromIndex:thisCellContent.length-4];
        if ([str isEqualToString:@"</p>"]) {       //说明这个cell里没有图片
            cell.content = [thisCellContent substringToIndex:thisCellContent.length-4];
            cell.imgInfoArray = nil;
            
        } else {                        //这个cell里面有图片
            //这个字典可能是是两个元素，第一个是文字，第二个是图片们；
            //也有可能直接是图片们
            NSArray* arr = [thisCellContent componentsSeparatedByString:@"</p>"];
            NSString* imgStrs = nil;
            if (arr.count == 2) {       //文字+图片组合
                cell.content = arr[0];
                imgStrs = arr[1];
            } else {                    //直接就是图片
                cell.content = nil;
                imgStrs = thisCellContent;
            }
            
            //注意这里可能会有多张图片.他可能长这样“<!--IMG#0--><!--IMG#1--><!--IMG#2-->”,代表三张图片
            NSArray* imgRefArray = [imgStrs componentsSeparatedByString:@"<"];  //长这样“!--IMG#0-->”“!--IMG#1-->”
            NSMutableArray* imgInfoArray = [[NSMutableArray alloc] init];       //这个数组是要传给cell的
            NSArray* imgArray = _newsDetailModel.imgArray;                      //数据模型里面拿出的数组
            //遍历数组，把对应的照片信息找出来
            for (int i = 0; i < imgRefArray.count-1; i++) {
                for (int j = 0; j < imgArray.count; j++) {
                    NSDictionary* dic = imgArray[j];
                    NSString* ref = [dic[@"ref"] substringFromIndex:1];            //也长这样“!--IMG#0-->”
                    if ([imgRefArray[i+1] isEqualToString:ref]) {
                        //对上号，就拿出来
                        [imgInfoArray addObject:dic];
                    }
                }
            }
            
            cell.imgInfoArray = imgInfoArray;
        }
    } else {
        cell.content = thisCellContent;
        cell.imgInfoArray = nil;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat height = 0;
    
    NSString* newsBody = _newsDetailModel.newsBody;
    NSArray* cellContentArray = [newsBody componentsSeparatedByString:@"<p>"];
    
    NSString* thisCellContent = cellContentArray[indexPath.row];        //这个cell的内容
    if (thisCellContent.length >= 4) {          //虽然我知道他一定存在
        NSString* str = [thisCellContent substringFromIndex:thisCellContent.length-4];
        if ([str isEqualToString:@"</p>"]) {       //说明这个cell里没有图片
            NSString* content = [thisCellContent substringToIndex:thisCellContent.length-4];
            height = [Tools contentSizeWithMaxWidth:kWidth-20 text:content fontOfSize:14].height;
            height += 5*(height/30);
            
        } else {                        //这个cell里面有图片
            //这个字典可能是两个元素，第一个是文字，第二个是图片们；
            //也有可能直接就是图片们,这样的话里面就不含</p>
            NSArray* arr = [thisCellContent componentsSeparatedByString:@"</p>"];
            NSString* content = nil;
            NSString* imgStrs = nil;
            if (arr.count == 2) {           //文字+图片
                content = arr[0];
                imgStrs = arr[1];
            } else imgStrs = thisCellContent;//只有图片
            
            //注意这里可能会有多张图片.他可能长这样“<!--IMG#0--><!--IMG#1--><!--IMG#2-->”,代表三张图片
            NSArray* imgRefArray = [imgStrs componentsSeparatedByString:@"<"];  //长这样“!--IMG#0-->”“!--IMG#1-->”
            NSMutableArray* imgHeightArray = [[NSMutableArray alloc] init];       //这个数组存储着各个图片的高度
            NSArray* imgArray = _newsDetailModel.imgArray;                      //数据模型里面拿出的数组
            //遍历数组，把对应的照片信息找出来
            //这里需要注意一个问题，分割出来的 存入数组中，数组中的第一个元素一定是：“”。所以不要考虑它
            for (int i = 0; i < imgRefArray.count-1; i++) {
                for (int j = 0; j < imgArray.count; j++) {
                    NSDictionary* dic = imgArray[j];
                    NSString* ref = [dic[@"ref"] substringFromIndex:1];            //也长这样“!--IMG#0-->”
                    if ([imgRefArray[i+1] isEqualToString:ref]) {
                        //对上号，就计算图片的高度吧
                        NSString* pixel = dic[@"pixel"];
                        NSArray* pixelArray = [pixel componentsSeparatedByString:@"*"];
                        if (pixelArray.count == 2) {    //如果有图片的尺寸告诉我，我就按尺寸计算
                            CGFloat oldWidth = [pixelArray[0] floatValue];
                            CGFloat oldHeight = [pixelArray[1] floatValue];
                            CGFloat thisHeight = oldHeight/oldWidth*(kWidth-20)+20; //也再送20
                            NSString* alt = dic[@"alt"];
                            if (alt.length) thisHeight += 20;       //如果有图片说明，就再加20
                            [imgHeightArray addObject:[NSNumber numberWithFloat:thisHeight]];
                        } else {        //如果没有图片的尺寸给我，我就默认为200
                            CGFloat thisHeight = 200+20;//再送20
                            NSString* alt = dic[@"alt"];
                            if (alt.length) thisHeight += 20;       //如果有图片说明，就再加20
                            [imgHeightArray addObject:[NSNumber numberWithFloat:thisHeight]];
                        }
                    }
                }
            }
            for (NSNumber* oneHeight in imgHeightArray) {
                height += [oneHeight floatValue];
            }
            //因为行间距为5，所以要把这个算在内
            CGFloat labelHeight = [Tools contentSizeWithMaxWidth:kWidth-20 text:content fontOfSize:14].height;
            labelHeight += (labelHeight/20)*5;
            //如果有文字，再加上文字的高度
            if (content.length) height += labelHeight;
        }
    } else {
        return 2;
    }
    
    return height+30;
}


@end
